package com.xxx.video.commen.views;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;

import butterknife.ButterKnife;

public abstract class BasePopupWindow extends PopupWindow {

    public Context context;

    public BasePopupWindow(@NonNull Context context) {
        super(context);
        this.context = context;
        View view = LayoutInflater.from(context).inflate(getContentLayout(), null);
        setContentView(view);
        ButterKnife.bind(this, view);
        this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setFocusable(true);
        setTouchable(true);
        setOutsideTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xffffff);
        setBackgroundDrawable(dw);
        initView(view);
        initListener();
        initData();
    }

    /**
     * get layout id
     *
     * @return layout id
     */
    public abstract int getContentLayout();

    /**
     * init data
     */
    protected abstract void initData();

    /**
     * init listener
     */
    protected abstract void initListener();

    /**
     * init view
     *
     * @param view view
     */
    protected abstract void initView(View view);

    @Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT < 24) {
            super.showAsDropDown(anchor);
        } else {
            int[] location = new int[2];
            anchor.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            showAtLocation(anchor, Gravity.NO_GRAVITY, 0, y + anchor.getHeight());
        }
    }

    /**
     * show the screen bottom
     *
     * @param view layout view
     */
    public void showAtLocation(View view) {
        if (this.isShowing()) {
            return;
        }
        showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
